package com.whmnx.main.ui.videorecord;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.classic.adapter.CommonRecyclerAdapter;
import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.qcloud.ugckit.UGCKitConstants;
import com.tencent.qcloud.ugckit.utils.LogReport;
import com.tencent.qcloud.ugckit.utils.TelephonyUtil;
import com.tencent.qcloud.ugckit.utils.ToastUtil;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLog;
import com.tencent.rtmp.TXVodPlayConfig;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.whmnx.base.bean.BaseBean;
import com.whmnx.base.bean.PingBean;
import com.whmnx.base.bean.ShopShowBean;
import com.whmnx.base.bean.TCVideoInfo;
import com.whmnx.base.bean.TolalBean;
import com.whmnx.base.bean.VideoListBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.router.RouterActivityPath;
import com.whmnx.base.utils.ImageUtil;
import com.whmnx.base.utils.TCTimeUtil;
import com.whmnx.base.view.DynamicInputTextMsgDialog;
import com.whmnx.base.view.TCPointSeekBar;
import com.whmnx.main.R;
import com.whmnx.main.ui.activity.PersonalActivity2;
import com.whmnx.main.ui.adapter.PingJiaListAdapter;
import com.whmnx.main.ui.adapter.ShowShopAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import de.hdodenhof.circleimageview.CircleImageView;
import fr.castorflex.android.verticalviewpager.VerticalViewPager;
import io.reactivex.annotations.Nullable;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.SPUtils;

/**
 * @author Administrator
 */
public class TCVodPlayerActivity extends Activity implements  TelephonyUtil.OnTelephoneListener {
    private static final String TAG = "TCVodPlayerActivity";
    private VerticalViewPager mVerticalViewPager;
    private MyPagerAdapter mPagerAdapter;
    private TXCloudVideoView mTXCloudVideoView;
    private TextView mTvBack;
    private ImageView mIvCover;
    // 合拍相关
    private ImageButton mImgBtnFollowShot;
    // 发布者id 、视频地址、 发布者名称、 头像URL、 封面URL
    private List<TCVideoInfo> mTCLiveInfoList;
    private int mInitTCLiveInfoPosition;
    private int mCurrentPosition;

    private List<PingBean> pingBeanList = new ArrayList<>();


    private PingJiaListAdapter pingJiaListAdapter;
    private TextView tvNme;

    private int pos;

    private List<VideoListBean> videoListBean;

    public List<Boolean> alreadyLikeList = new ArrayList<>();

    private DynamicInputTextMsgDialog dynamicInputTextMsgDialog;

    /**
     * SDK播放器以及配置
     */
    private TXVodPlayer mTXVodPlayer;
    private boolean isAdapterFlag = false;

    private Dialog dialogHead;
    private int dianType;

    private int showType1;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        initDatas();
        initInput();
        initViews();
        initPlayerSDK();

        TelephonyUtil.getInstance().setOnTelephoneListener(this);
        TelephonyUtil.getInstance().initPhoneListener();

        //在这里停留，让列表界面卡住几百毫秒，给sdk一点预加载的时间，形成秒开的视觉效果
       /* try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }

    private void initInput() {
        dynamicInputTextMsgDialog = new DynamicInputTextMsgDialog(this);

        dynamicInputTextMsgDialog.setOnSendClickListener(new DynamicInputTextMsgDialog.OnSendClickListener() {
            @Override
            public void onSendClick(String text) {

            }
        });
    }

    private void initDatas() {
        Intent intent = getIntent();
        mTCLiveInfoList = (List<TCVideoInfo>) intent.getSerializableExtra(UGCKitConstants.TCLIVE_INFO_LIST);
        videoListBean = (List<VideoListBean>) intent.getSerializableExtra(UGCKitConstants.TIMESTAMP);
        dianType = intent.getIntExtra(UGCKitConstants.PUSHER_ID,0);
        mInitTCLiveInfoPosition = intent.getIntExtra(UGCKitConstants.TCLIVE_INFO_POSITION, 0);
    }

    private void initViews() {
        mTXCloudVideoView = (TXCloudVideoView) findViewById(R.id.player_cloud_view);
        mIvCover = (ImageView) findViewById(R.id.player_iv_cover);
        mTvBack = (TextView) findViewById(R.id.player_tv_back);
        mTvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mImgBtnFollowShot = (ImageButton) findViewById(R.id.imgBtn_follow_shot);
        mImgBtnFollowShot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 上报合唱
                LogReport.getInstance().reportChorus();
                // 合拍之前先下载视频

             /*   TCVideoInfo tcVideoInfo = mTCLiveInfoList.get(mCurrentPosition);
                FollowRecordDownloader downloader = new FollowRecordDownloader(TCVodPlayerActivity.this);
                downloader.setDuration(mTXVodPlayer.getDuration());
                downloader.downloadVideo(tcVideoInfo);*/
            }
        });
        mVerticalViewPager = (VerticalViewPager) findViewById(R.id.vertical_view_pager);
        mVerticalViewPager.setOffscreenPageLimit(2);
        mVerticalViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                TXLog.d(TAG, "mVerticalViewPager, onPageScrolled position = " + position);
            }

            @Override
            public void onPageSelected(int position) {
                TXLog.d(TAG, "mVerticalViewPager, onPageSelected position = " + position);
                mCurrentPosition = position;
                // 滑动界面，首先让之前的播放器暂停，并seek到0
                TXLog.d(TAG, "滑动后，让之前的播放器暂停，mTXVodPlayer = " + mTXVodPlayer);
                if (mTXVodPlayer != null) {
                    mTXVodPlayer.seek(0);
                    mTXVodPlayer.pause();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        mVerticalViewPager.setPageTransformer(false, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                TXLog.d(TAG, "mVerticalViewPager, transformPage pisition = " + position + " mCurrentPosition" + mCurrentPosition);
                if (position != 0) {
                    return;
                }

                ViewGroup viewGroup = (ViewGroup) page;
                mIvCover = (ImageView) viewGroup.findViewById(R.id.player_iv_cover);
                mTXCloudVideoView = (TXCloudVideoView) viewGroup.findViewById(R.id.player_cloud_view);


                PlayerInfo playerInfo = mPagerAdapter.findPlayerInfo(mCurrentPosition);
                if (playerInfo != null) {
                    playerInfo.vodPlayer.resume();
                    mTXVodPlayer = playerInfo.vodPlayer;

                    playerInfo.vodPlayer.getDuration();
                    playerInfo.vodPlayer.getCurrentPlaybackTime();
                    float a = playerInfo.vodPlayer.getDuration() / playerInfo.vodPlayer.getCurrentPlaybackTime();
                    KLog.json("hhh",a + "");
                }
            }
        });

        mPagerAdapter = new MyPagerAdapter();
        mVerticalViewPager.setAdapter(mPagerAdapter);
    }



    class MyPagerAdapter extends PagerAdapter   {

        private List<VideoListBean.CarouselProductModelBean> carouselProductModel;
        ArrayList<PlayerInfo> playerInfoList = new ArrayList<>();
        private int progress2;

        //暂停见
        private boolean isPause;

        protected PlayerInfo instantiatePlayerInfo(int position) {
            TXCLog.d(TAG, "instantiatePlayerInfo " + position);

            PlayerInfo playerInfo = new PlayerInfo();
            TXVodPlayer vodPlayer = new TXVodPlayer(TCVodPlayerActivity.this);
            vodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
            //FIXBUG:FULL_SCREEN 合唱显示不全，ADJUST_RESOLUTION黑边
           // vodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);


            TXVodPlayConfig config = new TXVodPlayConfig();

            //指定一个本地mp4缓存目录
            File sdcardDir = getExternalFilesDir(null);
            if (sdcardDir != null) {
                config.setCacheFolderPath(sdcardDir.getAbsolutePath() + "/txcache");
            }
            config.setMaxCacheItems(5);
            vodPlayer.setConfig(config);
            vodPlayer.setAutoPlay(false);

            TCVideoInfo tcLiveInfo = mTCLiveInfoList.get(position);
            playerInfo.playURL = TextUtils.isEmpty(tcLiveInfo.hlsPlayUrl) ? tcLiveInfo.playurl : tcLiveInfo.hlsPlayUrl;
            playerInfo.vodPlayer = vodPlayer;
            playerInfo.reviewstatus = tcLiveInfo.review_status;
            playerInfo.pos = position;
            playerInfoList.add(playerInfo);

            return playerInfo;
        }

        protected void destroyPlayerInfo(int position) {
            while (true) {
                PlayerInfo playerInfo = findPlayerInfo(position);
                if (playerInfo == null) {
                    break;
                }
                playerInfo.vodPlayer.stopPlay(true);
                playerInfoList.remove(playerInfo);

                TXCLog.d(TAG, "destroyPlayerInfo " + position);
            }
        }

        public PlayerInfo findPlayerInfo(int position) {
            for (int i = 0; i < playerInfoList.size(); i++) {
                PlayerInfo playerInfo = playerInfoList.get(i);
                if (playerInfo.pos == position) {
                    return playerInfo;
                }
            }
            return null;
        }

        public PlayerInfo findPlayerInfo(TXVodPlayer player) {
            for (int i = 0; i < playerInfoList.size(); i++) {
                PlayerInfo playerInfo = playerInfoList.get(i);
                if (playerInfo.vodPlayer == player) {
                    return playerInfo;
                }
            }
            return null;
        }

        public void onDestroy() {
            for (PlayerInfo playerInfo : playerInfoList) {
                playerInfo.vodPlayer.stopPlay(true);
            }
            playerInfoList.clear();
        }

        @Override
        public int getCount() {
            return mTCLiveInfoList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            TXCLog.i(TAG, "MyPagerAdapter instantiateItem, position = " + position);
            TCVideoInfo videoInfo = mTCLiveInfoList.get(position);

            View view = LayoutInflater.from(container.getContext()).inflate(R.layout.view_player_content4, null);
            view.setId(position);

            // 封面
           /* ImageView coverImageView = (ImageView) view.findViewById(R.id.player_iv_cover);
            if (videoInfo.review_status == TCVideoInfo.REVIEW_STATUS_PORN) { //涉黄的图片不显示
                coverImageView.setImageResource(R.drawable.bg);
            } else {
                BitmapUtils.blurBgPic(TCVodPlayerActivity.this, coverImageView, videoInfo.frontcover, R.drawable.bg);
            }*/


          /*  TextView tvStatus = (TextView) view.findViewById(R.id.tx_video_review_status);
            if (videoInfo.review_status == TCVideoInfo.REVIEW_STATUS_NOT_REVIEW) {
                tvStatus.setVisibility(View.VISIBLE);
                tvStatus.setText(R.string.video_not_review);
            } else if (videoInfo.review_status == TCVideoInfo.REVIEW_STATUS_PORN) {
                tvStatus.setVisibility(View.VISIBLE);
                tvStatus.setText(R.string.video_porn);
            } else if (videoInfo.review_status == TCVideoInfo.REVIEW_STATUS_NORMAL) {
                tvStatus.setVisibility(View.GONE);
            }*/

            // 获取此player
            TXCloudVideoView playView = (TXCloudVideoView) view.findViewById(R.id.player_cloud_view);
            RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.rl);
            //进度条
            TCPointSeekBar mSeekBarProgress = (TCPointSeekBar) view.findViewById(R.id.superplayer_seekbar_progress);

            final TextView mTvCurrent = (TextView) view.findViewById(R.id.superplayer_tv_current);

            final TextView  mTvDuration = (TextView) view.findViewById(R.id.superplayer_tv_duration);
            final ImageView  ivReview = (ImageView) view.findViewById(R.id.tx_video_review_status);

            CircleImageView playerCiv = (CircleImageView) view.findViewById(R.id.player_civ_avatar);
            ImageView ivAdd = (ImageView) view.findViewById(R.id.iv_add);
            ImageView  tvJian = (ImageView) view.findViewById(R.id.tv_jianzan);
            TextView  tvMsg = (TextView) view.findViewById(R.id.tv_msg);
            TextView  tvFan = (TextView) view.findViewById(R.id.tv_fan);
            TextView  tvName = (TextView) view.findViewById(R.id.tv_name);
            TextView  tvTitle = (TextView) view.findViewById(R.id.tv_title);
            TextView  tvInput = (TextView) view.findViewById(R.id.tv_input);
            TextView  tvLike = (TextView) view.findViewById(R.id.tv_like);
            LinearLayout llJianzan = (LinearLayout) view.findViewById(R.id.ll_jianzan);

            RelativeLayout  rlModel = (RelativeLayout) view.findViewById(R.id.rl_model);
            TextView  tv1 = (TextView) view.findViewById(R.id.tv1);
            TextView  tv2 = (TextView) view.findViewById(R.id.tv2);
            CircleImageView  ivCV = (CircleImageView) view.findViewById(R.id.iv_cv);

            VideoListBean videoBean =  videoListBean.get(position);

            String userId =  SPUtils.getInstance().getString(Constants.USERID);


            carouselProductModel = videoBean.getCarouselProductModel();
            if (carouselProductModel.size()>0){
                rlModel.setVisibility(View.VISIBLE);
                tv1.setText(carouselProductModel.get(0).getName());
                tv2.setText("￥" + carouselProductModel.get(0).getPrice());
                ImageUtil.setImage(ivCV,carouselProductModel.get(0).getImg());
            }else {
                rlModel.setVisibility(View.GONE);
            }

            rlModel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SPUtils.getInstance().put("Product_Id", carouselProductModel.get(0).getId());
                    ARouter.getInstance().build(RouterActivityPath.Main.ORDER).navigation();
                }
            });

            ImageUtil.setImage(playerCiv,videoBean.getWork_UserInfoImage());


            if (videoBean.getWork_UserInfoId().equals(userId)){
                ivAdd.setVisibility(View.INVISIBLE);
            }else {
                //0 是否关注
                if (videoBean.getIsFocus() == 0){
                    ivAdd.setVisibility(View.VISIBLE);
                }else {
                    ivAdd.setVisibility(View.INVISIBLE);
                }
            }


            Constants.alreadyLikeList.add(videoBean.getIsLike() == 1);  // 已点赞
            if (isAdapterFlag){
                if (Constants.alreadyLikeList.get(0)){
                    tvJian.setImageResource(R.mipmap.live);
                }else {
                    tvJian.setImageResource(R.mipmap.dianzai3);  //未点赞
                }
            }else {
                if (Constants.alreadyLikeList.get(position)){
                    tvJian.setImageResource(R.mipmap.live);
                }else {
                    tvJian.setImageResource(R.mipmap.dianzai3);  //未点赞
                }
            }
            // alreadyLikeList.set(position,videoBean.getIsLike() == 1);  // 已点赞

            //0 未点赞  1 已点赞
          /*  if (videoBean.getIsLike() == 0){
                tvJian.setImageResource(R.mipmap.live);
            }else {
                tvJian.setImageResource(R.mipmap.dianzai3);
            }*/
            //  tvLike.setText(videoBean.getWoek_LikeNumber() + "");
            tvMsg.setText(videoBean.getWork_RemarkNumber() + "");
            tvFan.setText(videoBean.getWork_ForwardNumber() + "");
            tvName.setText(videoBean.getWork_UserInfoName());
            tvTitle.setText(videoBean.getWork_Title());

            //加关注
            ivAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("UserId", SPUtils.getInstance().getString(Constants.USERID));
                    params.put("FollowUserId",videoBean.getWork_UserInfoId());
                    HttpClient.get(TCVodPlayerActivity.this, Constants.ADDFOLLOW, params,new CallBack<BaseBean>() {
                        @Override
                        public void onSuccess(BaseBean baseBean) {
                            ivAdd.setVisibility(View.GONE);
                            videoBean.setIsFocus(1);
                            // initDatas();
                        }
                    });
                }
            });

            //点赞
            llJianzan.setOnClickListener(v -> {
                Map<String, Object> params = new HashMap<>();
                params.put("uId", SPUtils.getInstance().getString(Constants.USERID));
                params.put("vId",videoBean.getWork_Id());

                if (isAdapterFlag){
                    if (Constants.alreadyLikeList.get(0)){
                        params.put("status", 0 + ""); //取消点赞
                    }else {
                        params.put("status",1 + ""); //点赞
                    }
                }else {
                    if (dianType == 2){
                        if (Constants.alreadyLikeList.get(position)){
                            params.put("status", 0 + ""); //取消点赞
                        }else {
                            params.put("status",1 + ""); //点赞
                        }
                    }else {
                        if (Constants.alreadyLikeList2.get(position)){
                            params.put("status", 0 + ""); //取消点赞
                        }else {
                            params.put("status",1 + ""); //点赞
                        }
                    }
                }



                HttpClient.get(TCVodPlayerActivity.this, Constants.GIVELIKE, params,new CallBack<String>() {
                    @Override
                    public void onSuccess(String baseBean) {
                        if (isAdapterFlag){
                            if (alreadyLikeList.get(0)){
                                tvJian.setImageResource(R.mipmap.dianzai3);
                                alreadyLikeList.set(position,false);
                            }else {
                                tvJian.setImageResource(R.mipmap.live);
                                alreadyLikeList.set(position,true);
                            }
                        }else {
                            if (dianType == 2){
                                if (Constants.alreadyLikeList.get(position)){
                                    tvJian.setImageResource(R.mipmap.dianzai3);
                                    Constants.alreadyLikeList.set(position,false);
                                    RxBus.getDefault().post(EventConstants.LIVE);
                                }else{
                                    tvJian.setImageResource(R.mipmap.live);
                                    Constants.alreadyLikeList.set(position,true);
                                    RxBus.getDefault().post(EventConstants.LIVE);
                                }
                            }else {
                                if (Constants.alreadyLikeList2.get(position)){
                                    tvJian.setImageResource(R.mipmap.dianzai3);
                                    Constants.alreadyLikeList2.set(position,false);
                                }else{
                                    tvJian.setImageResource(R.mipmap.live);
                                    Constants.alreadyLikeList2.set(position,true);
                                }
                            }

                        }
                    }
                });
            });

            tvFan.setOnClickListener(v -> {
                showFanDialog(videoBean);
            });

            //评价
            tvMsg.setOnClickListener(v -> {
                showPinDialog(videoBean);
            });

            tvInput.setOnClickListener(v -> {
                showDialog(videoBean);
            });


            PlayerInfo playerInfo = instantiatePlayerInfo(position);
            playerInfo.playerView = playView;
            playerInfo.vodPlayer.setPlayerView(playView);

            playerInfo.vodPlayer.startPlay(playerInfo.playURL);

            if (playerInfo.vodPlayer.isPlaying()){
                // ivReview.setVisibility(View.GONE);
            }

            playView.setOnClickListener(v -> {
                isPause = false;
                if (playerInfo.vodPlayer.isPlaying()){
                    playerInfo.vodPlayer.pause();
                    ivReview.setVisibility(View.VISIBLE);
                }else {
                    playerInfo.vodPlayer.resume();
                    ivReview.setVisibility(View.INVISIBLE);
                }
            });

            /**
             * 主页
             */
            playerCiv.setOnClickListener(v -> {
              //  Constants.UID = videoBean.getWork_UserInfoId();
              //  Constants.ISFOCUS = videoBean.getIsFocus();
              //  ARouter.getInstance().build(RouterActivityPath.Home.PESON).navigation();

                startActivity(new Intent(TCVodPlayerActivity.this, PersonalActivity2.class).putExtra("uId", videoBean.getWork_UserInfoId())
                        .putExtra("IsFocus", videoBean.getIsFocus()));
                playerInfo.vodPlayer.pause();
                isPause = true;
            });

            //监听播放
            playerInfo.vodPlayer.setVodListener(new ITXVodPlayListener() {
                @Override
                public void onPlayEvent(TXVodPlayer player, int event, Bundle param) {
                    if (event == TXLiveConstants.PLAY_EVT_CHANGE_RESOLUTION) {
                        int width = param.getInt(TXLiveConstants.EVT_PARAM1);
                        int height = param.getInt(TXLiveConstants.EVT_PARAM2);
                        //FIXBUG:不能修改为横屏，合唱会变为横向的
                    } else if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {   //播放完成
                        if (videoBean.getIsLook() == 0) { //0 未看过  1 是看过（全部看完）
                            lookWorkrecord(videoBean);
                        }

                        restartPlay();
                    } else if (event == TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME) {// 视频I帧到达，开始播放
                        PlayerInfo playerInfo = mPagerAdapter.findPlayerInfo(player);
                        if (playerInfo != null) {
                            playerInfo.isBegin = true;
                        }
                        if (mTXVodPlayer == player) {
                            TXLog.i(TAG, "onPlayEvent, event I FRAME, player = " + player);
                            //   mIvCover.setVisibility(View.GONE);

                            //   LogReport.getInstance().reportVodPlaySucc(event);
                        }

                    } else if (event == TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED) {   //准备播放
                        if (mTXVodPlayer == player) {
                            TXLog.i(TAG, "onPlayEvent, event prepared, player = " + player);
                            mTXVodPlayer.resume();
                        }

                    } else if (event == TXLiveConstants.PLAY_EVT_PLAY_BEGIN) { //开始播放
                       PlayerInfo playerInfo = mPagerAdapter.findPlayerInfo(player);
                        if (playerInfo != null && playerInfo.isBegin) {
                            // mIvCover.setVisibility(View.GONE);
                            TXCLog.i(TAG, "onPlayEvent, event begin, cover remove");
                            //  playerInfo.vodPlayer.pause();
                            ivReview.setVisibility(View.GONE);
                            if (isPause){
                                playerInfo.vodPlayer.pause();
                            }
                        }
                    } else if (event < 0) {
                        if (mTXVodPlayer == player) {
                            TXLog.i(TAG, "onPlayEvent, event prepared, player = " + player);

                            // LogReport.getInstance().reportVodPlayFail(event);
                        }
                        // ToastUtil.toastShortMessage("event:" + event);
                    }else if (event == TXLiveConstants.PLAY_EVT_PLAY_PROGRESS){

                        int progress = param.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);
                        KLog.i(progress + "");
                        int duration = param.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);

                        mTvCurrent.setText(TCTimeUtil.formattedTime(progress));

                        mTvDuration.setText(TCTimeUtil.formattedTime(duration));

                        KLog.i(progress / 1000 + "----progress");
                        KLog.i(duration / 1000 + "----duration");

                        //   updateVideoProgress(progress / 1000, duration / 1000);
                        //总时长
                        // playerInfo.vodPlayer.getDuration();

                        //  playerInfo.vodPlayer.getCurrentPlaybackTime();

                        //  playerInfo.vodPlayer.getPlayableDuration();

                        //   KLog.i(playerInfo.vodPlayer.getCurrentPlaybackTime() + "----getCurrentPlaybackTime");
                        //    KLog.i(playerInfo.vodPlayer.getPlayableDuration() + "----getPlayableDuration");
                        //    KLog.i(playerInfo.vodPlayer.getDuration() + "----getDuration");

                        float percentage = (duration/1000) > 0 ? ((float) (progress/1000)  / (float) (duration/1000) ) : 1.0f;
                        int  progress2 = Math.round(percentage * mSeekBarProgress.getMax());

                        mSeekBarProgress.setProgress(progress2);

                        //   updateVideoProgress(playerInfo.vodPlayer.getPlayableDuration(), playerInfo.vodPlayer.getDuration());

                        // KLog.i(progress  / duration );
                    }
                }

                @Override
                public void onNetStatus(TXVodPlayer txVodPlayer, Bundle bundle) {

                }
            });

            playerInfo.vodPlayer.getDuration();
            playerInfo.vodPlayer.getCurrentPlaybackTime();
            float a = playerInfo.vodPlayer.getCurrentPlaybackTime() / playerInfo.vodPlayer.getDuration();
            KLog.json("hhh",a + "");

            container.addView(view);
            return view;
        }

        private void showDialog(VideoListBean videoBean) {
            dialogHead = new Dialog(TCVodPlayerActivity.this, R.style.ActionSheetDialogStyle);
            View view = LayoutInflater.from(TCVodPlayerActivity.this).inflate(R.layout.dialog_video, null);
            RecyclerView rlShop = view.findViewById(R.id.rl_shop);
            TextView tvNme = view.findViewById(R.id.tv_num);
            LinearLayoutManager layoutManager = new LinearLayoutManager(TCVodPlayerActivity.this);
            //配置布局，默认为vertical（垂直布局），下边这句将布局改为水平布局
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            rlShop.setLayoutManager(layoutManager);
            rlShop.setItemAnimator(new DefaultItemAnimator());
            ShowShopAdapter showShopAdapter = new ShowShopAdapter(TCVodPlayerActivity.this);
            rlShop.setAdapter(showShopAdapter);


            view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialogHead.dismiss();
                }
            });

            dialogHead.setContentView(view);
            Window window = dialogHead.getWindow();
            if (window == null) {
                return;
            }
            //宽高最大
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
            //显示对话框//设置Dialog从窗体底部弹出
            dialogHead.setCanceledOnTouchOutside(true);
            dialogHead.show();
            window.setGravity(Gravity.BOTTOM);
            //获取窗体的属性
            WindowManager.LayoutParams lp = window.getAttributes();
            //设置Dialog距离底部的距离
            //将属性设置给窗体
            window.setAttributes(lp);


            Map<String, Object> params = new HashMap<>();
            params.put("uId", videoBean.getWork_UserInfoId());
            params.put("pageIndex", 1);
            params.put("pageSize", 10);
            HttpClient.post(view.getContext(), Constants.WORKPRODUCTLIST, params,new CallBack<List<ShopShowBean>>() {
                @Override
                public void onSuccess(List<ShopShowBean> shopShowBeans) {
                    showShopAdapter.replaceAll(shopShowBeans, true);
                    tvNme.setText("共" + shopShowBeans.size() + "件商品");
                }
            });
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            TXCLog.i(TAG, "MyPagerAdapter destroyItem, position = " + position);

            destroyPlayerInfo(position);

            container.removeView((View) object);
        }
    }

    /**
     视频观看记录
     */
    private void lookWorkrecord(VideoListBean videoBean) {
        Map<String, Object> params = new HashMap<>();
        params.put("wId",videoBean.getWork_Id());
        params.put("uId",SPUtils.getInstance().getString(Constants.USERID));
        HttpClient.get(this, Constants.LOOKWORKRECORD, params,new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean result) {
                videoBean.setIsLook(1);
            }
        });
    }


    private String remark_id;
    private String replyId;
    /**
     * 评价
     * @param videoBean
     */
    private void showPinDialog(VideoListBean videoBean) {
        Dialog  dialogHead = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_video, null);
        RecyclerView rlShop = view.findViewById(R.id.rl_shop);
        tvNme = view.findViewById(R.id.tv_num);
        LinearLayout llSend = view.findViewById(R.id.ll_send_or_cancel);
        TextView etInput = view.findViewById(R.id.et_input_message);
        TextView tvSend = view.findViewById(R.id.tv_send);

        llSend.setVisibility(View.VISIBLE);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //配置布局，默认为vertical（垂直布局），下边这句将布局改为水平布局
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rlShop.setLayoutManager(layoutManager);
        rlShop.setItemAnimator(new DefaultItemAnimator());
        pingJiaListAdapter = new PingJiaListAdapter(this);
        rlShop.setAdapter(pingJiaListAdapter);


        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogHead.dismiss();
            }
        });

        etInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showType1 = 1;
                dynamicInputTextMsgDialog.setShowType();

            }
        });


        dynamicInputTextMsgDialog.setOnSendClickListener(new DynamicInputTextMsgDialog.OnSendClickListener() {
            @Override
            public void onSendClick(String etInput) {
                if (TextUtils.isEmpty(etInput)){
                    ToastUtil.toastShortMessage("请输入评价内容");
                    return;
                }
                if (showType1 == 1){
                    Map<String, Object> params = new HashMap<>();
                    params.put("userId", SPUtils.getInstance().getString(Constants.USERID));
                    params.put("parentId","");
                    params.put("replyId","");
                    params.put("remark_Content",etInput);
                    params.put("workId",videoBean.getWork_Id());
                    HttpClient.post(TCVodPlayerActivity.this, Constants.ADDREMARK, params,new CallBack<TolalBean>() {
                        @Override
                        public void onSuccess(TolalBean result) {
                            remarkList(videoBean);
                        }
                    });
                }else {
                    Map<String, Object> params = new HashMap<>();
                    params.put("userId", SPUtils.getInstance().getString(Constants.USERID));
                    params.put("parentId",remark_id);
                    params.put("replyId",replyId);
                    params.put("remark_Content",etInput);
                    params.put("workId",videoBean.getWork_Id());
                    HttpClient.post(TCVodPlayerActivity.this, Constants.ADDREMARK, params,new CallBack<TolalBean>() {
                        @Override
                        public void onSuccess(TolalBean result) {
                            remarkList(videoBean);

                          /*  Map<String, Object> params = new HashMap<>();
                            params.put("workId", videoBean.getWork_Id());
                            params.put("parentId", remark_id);
                            params.put("pageIndex",pos + 1);
                            params.put("pageSize",10);
                            HttpClient.post(getActivity(), Constants.CHILDREMARKLIST, params,new CallBack<List<PingBean>>() {
                                @Override
                                public void onSuccess(List<PingBean> pingBeans) {

                                }
                            });*/
                        }
                    });
                }
            }
        });



        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        //宽高最大
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        //显示对话框//设置Dialog从窗体底部弹出
        dialogHead.setCanceledOnTouchOutside(true);
        dialogHead.show();
        window.setGravity(Gravity.BOTTOM);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置Dialog距离底部的距离
        //将属性设置给窗体
        window.setAttributes(lp);

        remarkList(videoBean);


        pingJiaListAdapter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                showType1 = 2;
                pos = i;
                dynamicInputTextMsgDialog.setShowType();
                remark_id = pingBeanList.get(i).getRemark_Id();
                dynamicInputTextMsgDialog.etInputMessage.setText("@" + pingBeanList.get(i).getUserName() + " ");
                dynamicInputTextMsgDialog.etInputMessage.setSelection(dynamicInputTextMsgDialog.etInputMessage.getText().toString().length());
            }
        });

        pingJiaListAdapter.setOnSendClickListener(new PingJiaListAdapter.OnSetClickListener() {
            @Override
            public void onSendClick(String text, String text2,String name) {
                showType1 = 2;
                remark_id = text;
                replyId = text2;
                dynamicInputTextMsgDialog.setShowType();
                dynamicInputTextMsgDialog.etInputMessage.setText("@" + name);
                dynamicInputTextMsgDialog.etInputMessage.setSelection(dynamicInputTextMsgDialog.etInputMessage.getText().toString().length());
            }
        });

    }


    /**
     * 评价列表
     */
    private void remarkList(VideoListBean videoBean) {
        Map<String, Object> params = new HashMap<>();
        params.put("workId", videoBean.getWork_Id());
        params.put("pageIndex",1);
        params.put("pageSize",10);
        HttpClient.post(this, Constants.REMARKLIST, params,new CallBack<List<PingBean>>() {
            @Override
            public void onSuccess(List<PingBean> pingBeans) {
                pingBeanList.clear();
                pingBeanList.addAll(pingBeans);
                pingJiaListAdapter.replaceAll(pingBeans,true);
                tvNme.setText("共" + pingBeans.size() + "条评论");
            }
        });
    }


    private void showFanDialog(VideoListBean videoBean) {
        Dialog dialogHead = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_fan, null);

        view.findViewById(R.id.ll_wei).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cn.sharesdk.framework.Platform platform = ShareSDK.getPlatform(Wechat.NAME);
                cn.sharesdk.framework.Platform.ShareParams shareParams = new  cn.sharesdk.framework.Platform.ShareParams();
                shareParams.setTitle("今网播");
                shareParams.setText("这是一个有趣的应用");
                //  shareParams.setImageUrl(videoBean.getWork_Image());
                shareParams.setImageUrl(videoBean.getWork_Image());
                shareParams.setUrl(videoBean.getWork_Vidoe());
                //分享网页
                shareParams.setShareType(4);
                platform.share(shareParams);
                dialogHead.dismiss();
            }
        });
        view.findViewById(R.id.ll_zhi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cn.sharesdk.framework.Platform platform = ShareSDK.getPlatform(WechatMoments.NAME);
                cn.sharesdk.framework.Platform.ShareParams shareParams = new  cn.sharesdk.framework.Platform.ShareParams();
                shareParams.setTitle("今网播");
                shareParams.setText("这是一个有趣的应用");
                //  shareParams.setImageUrl(videoBean.getWork_Image());
                shareParams.setImageUrl(videoBean.getWork_Image());
                shareParams.setUrl(videoBean.getWork_Vidoe());
                //分享网页
                shareParams.setShareType(4);
                platform.share(shareParams);
                dialogHead.dismiss();
            }
        });

        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        //宽高最大
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        //显示对话框//设置Dialog从窗体底部弹出
        dialogHead.setCanceledOnTouchOutside(true);
        dialogHead.show();
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置Dialog距离底部的距离
        //将属性设置给窗体
        window.setAttributes(lp);
    }

    private void initPlayerSDK() {
        mVerticalViewPager.setCurrentItem(mInitTCLiveInfoPosition);
    }

    private void restartPlay() {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.resume();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mTXCloudVideoView != null) {
            mTXCloudVideoView.onResume();
        }
        if (mTXVodPlayer != null) {
            mTXVodPlayer.resume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mTXCloudVideoView != null) {
            mTXCloudVideoView.onPause();
        }
        if (mTXVodPlayer != null) {
            mTXVodPlayer.pause();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTXCloudVideoView != null) {
            mTXCloudVideoView.onDestroy();
            mTXCloudVideoView = null;
        }

        mPagerAdapter.onDestroy();
        // true 代表清除最后一帧画面
        stopPlay(true);
        mTXVodPlayer = null;

        TelephonyUtil.getInstance().uninitPhoneListener();
    }

    protected void stopPlay(boolean clearLastFrame) {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.stopPlay(clearLastFrame);
        }
    }




    private void updateVideoProgress(float mProgress, float mDuration) {
     //   mControllerWindow.updateVideoProgress(current, duration);


     //   KLog.i(percentage + "");

    }



    @Override
    public void onRinging() {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.setMute(true);
        }
    }

    @Override
    public void onOffhook() {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.setMute(true);
        }
    }

    @Override
    public void onIdle() {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.setMute(false);
        }
    }

}
